#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils.util import datetime_now_str
from controls.mongo import db_shitouren as db
from pymongo import DESCENDING

# test start
# from pymongo import MongoClient
# client = MongoClient( etc.mongo_host, 27017 )
# db = client.test
# test end

# collection in mongodb
coll = db.sight_comment
"""db.sight_comment collection has
   cityid:          城市id(int)
   sightid:         景点id(int)
   userid:             用户id(int)
   content:         评论内容(str)
   ctime:           评论时间(str)
"""


def get_sight_comment(cityid, sightid, nums=50):
    '''get latest comments by cityid and sightid
    '''
    cond = {}
    if cityid: cond['cityid'] = int(cityid)
    if cityid and sightid: cond['sightid'] = int(sightid)
    comments = coll.find(
        cond, {'_id': 0, 'userid': 1, 'username': 1, 'content': 1, 'ctime': 1}
    ).sort('ctime', DESCENDING).limit(nums)

    # for item in comments :
    #    comments_list.append({'userid':item[u'userid'], 'content': item[u'content']})
    res = {}
    res['cityid'] = cityid
    res['sightid'] = sightid
    res['content'] = [{'userid': int(item[u'userid']), 'username': item[u'username'].encode('utf-8'),
                       'content': item[u'content'].encode('utf-8')} for item in comments]
    return res


def get_latest_comment(cityid=None, sightid=None, start=0, nums=50):
    '''get latest comments's list
    '''
    cond = {}
    if cityid: cond['cityid'] = int(cityid)
    if cityid and sightid: cond['sightid'] = int(sightid)
    # print cond

    comments = coll.find(cond).sort('ctime', DESCENDING).skip(start).limit(nums)
    res_list = [{'_id': item[u'_id'], 'cityid': int(item[u'cityid']), 'sightid': int(item[u'sightid']),
                 'userid': int(item[u'userid']),
                 'ctime': item[u'ctime'].encode('utf-8'), 'content': item[u'content'].encode('utf-8')} for item in
                comments]

    return res_list


def add_sight_comment(cityid, sightid, userid, comment, username):
    '''add a comment for a city's sight
    '''

    res = coll.insert({'cityid': cityid, 'sightid': sightid,
                       'userid': userid, 'username': username, 'content': comment, 'ctime': datetime_now_str()})

    return res


def del_comment_by_id(id):
    '''del a comment by _id
    res:{u'syncMillis': 0, u'ok': 1.0, u'err': None, u'writtenTo': None, u'connectionId': 29, u'n': 1}
    '''
    res = coll.remove({'_id': id})
    return res


if __name__ == "__main__":
    print 'main start'
    print '=============insert test data'
    add_sight_comment(99, 1, 123001, "001very well!")
    add_sight_comment(99, 1, 123001, "001 haha haha")
    add_sight_comment(99, 1, 123002, "002very well!")
    add_sight_comment(99, 1, 123003, "003very well!")
    add_sight_comment(99, 1, 123004, "004very well!")
    add_sight_comment(99, 1, 123001, "123001很棒")
    add_sight_comment(99, 2, 123005, "005very well!")
    xx = add_sight_comment(99, 2, 123001, "001very well!")
    print xx, type(xx)

    print '============='
    print get_sight_comment(99, 1, 3)
    print '============='
    print get_latest_comment()
    print '============='
    print get_latest_comment(sightid=2)
    print '============='
    print get_latest_comment(cityid=98)
    print '============='
    print get_latest_comment(cityid=99, sightid=1)
    print '=============remove test data'
    result = get_latest_comment(cityid=99)
    for item in result:
        print del_comment_by_id(item['_id'])
